//
//  DocumentManager.m
//  Pennyworth Punch Clock
//
//  Created by Chris Karr on 8/4/08.
//  Copyright 2008 Northwestern University. All rights reserved.
//

#import "DocumentManager.h"
#import "AppDelegate.h"

@implementation DocumentManager

@synthesize openFiles;
@synthesize documents;

- (void) awakeFromNib
{
	[[NSDistributedNotificationCenter defaultCenter] addObserver:self 
														selector:@selector(update:) 
															name:PREDICTION_FETCHED 
														  object:nil];
	
	[[NSNotificationCenter defaultCenter] addObserver:self 
											 selector:@selector(update:) 
												 name:PREDICTION_FETCHED 
											   object:nil];
	
	self.openFiles = [NSMutableArray array];
	self.documents = [NSMutableArray array];
	
	[openTable registerForDraggedTypes:[NSArray arrayWithObject:NSFilenamesPboardType]];
	[relatedTable registerForDraggedTypes:[NSArray arrayWithObject:NSFilenamesPboardType]];
	
	[openTable setVerticalMotionCanBeginDrag:YES];
	[relatedTable setVerticalMotionCanBeginDrag:YES];
}

- (void) update:(NSNotification *) theNote
{
	[self willChangeValueForKey:@"openFiles"];
	[self.openFiles removeAllObjects];
	
	NSArray * applications = [[NSWorkspace sharedWorkspace] launchedApplications];
	
	for (NSDictionary * app in applications)
	{
		NSString * appName = [app valueForKey:@"NSApplicationName"];
		
		NSString * scriptString = [NSString stringWithFormat:@"tell application \"%@\" to return path of documents", appName];
		
		NSAppleScript * script = [[NSAppleScript alloc] initWithSource:scriptString];
		
		NSAppleEventDescriptor * desc = [script executeAndReturnError:nil];
		
		if (desc != nil)
		{
			NSInteger i = 1;
			
			for (i = 1; i <= [desc numberOfItems]; i++)
			{
				NSString * filePath = [[desc descriptorAtIndex:i] stringValue];
				
				if (filePath != nil)
				{	
					if ([filePath rangeOfString:@":"].location != NSNotFound)
						filePath = [[(NSURL *) CFURLCreateWithFileSystemPath (kCFAllocatorDefault, (CFStringRef) filePath, kCFURLHFSPathStyle, [filePath hasSuffix:@":"]) autorelease] path];
					
					NSString * fileApp = nil;
					NSString * fileType = nil;
					
					if ([[NSWorkspace sharedWorkspace] getInfoForFile:filePath application:&fileApp type:&fileType])
					{
						NSMutableDictionary * fileDict = [NSMutableDictionary dictionary];
						[fileDict setValue:filePath forKey:PATH];
						[fileDict setValue:fileApp forKey:APP];
						[fileDict setValue:fileType forKey:TYPE];
						[fileDict setValue:[filePath lastPathComponent] forKey:NAME];
						
						[self.openFiles addObject:fileDict];
					}
				}
			}
			
			[script release];
		}
	}
	
	[self didChangeValueForKey:@"openFiles"];
}

- (IBAction) toggleRelatedFiles:(id) sender;
{
	[NSApp activateIgnoringOtherApps:YES];
	[window makeKeyAndOrderFront:sender];
}

@end
